<template>
  <div>
    <el-card>
      <el-row type="flex" justify="space-between	">
        <el-button
          type="primary"
          size="mini"
          @click="addFn"
        >添加分类</el-button>
        <el-input
          v-model.trim="search.titleContains"
          placeholder="请输入关键字"
          style="width: 50%"
          @keyup.enter.native="searchFn"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchFn" />
        </el-input>
      </el-row>
      <el-divider />
      <!-- 表格部分 -->
      <el-table :data="categoriesData" border style="width: 100%">
        <el-table-column label="头像" width="120">
          <template v-slot="{ row }">
            <img :src="row.image" style="width: 100px">
          </template>
        </el-table-column>
        <el-table-column label="标题" width="240" prop="title" />
        <el-table-column label="介绍" prop="desc" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              size="mini"
              type="primary"
              @click="editFn(row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="delFn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <!-- 分页器 -->
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        align="middle"
        :page-size="limit"
        @current-change="changeCur"
      />
    </el-card>

    <!-- 弹出框 -->
    <el-dialog :title="formData.id?'编辑分类':'新增分类'" :visible="dialogFormVisible" @close="closeFn">
      <el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="formData.title" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model.trim="formData.desc" />
        </el-form-item>
        <!-- 头像部分 -->
        <el-form-item label="封面">
          <uploadImg ref="imgUpload" />
          <!-- <el-upload
            action="#"
            :http-request="uploadFn"
            :file-list="fileList"
            list-type="picture-card"
            :limit="1"
            :on-remove="removeFn"
          >
            <i class="el-icon-plus" />
          </el-upload> -->
          <el-input v-model="formData.name" placeholder="强制设置图片跳过上传" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="confirmFn"
        >确 定</el-button>
        <el-button @click="closeFn">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { categoriesList, categoriesCount, addCategories, getCategory, updateCategory, delCategory } from '@/api/categories'
export default {
  data() {
    return {
      categoriesData: [],
      limit: 2, // 页面数量
      start: 0, // 从第几条开始
      total: 0,
      page: 1,
      search: {
        titleContains: ''// 模糊查询标题
      },
      dialogFormVisible: false, // 弹出窗提示
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      // 图片
      fileList: [],
      // 表单校验
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  async created() {
    this.categoriesList()

    // 获取分类数量
    const res = await categoriesCount()
    // console.log(75, res.data)
    this.total = res.data
  },
  methods: {
    // 封装更新图片代码
    updateImg() {
      const imgUpload = this.$refs.imgUpload
      // 添加判断，当图片上传成功后再更新头像
      if (imgUpload.percentage !== 100) {
        return this.$message({
          type: 'warning',
          message: '头像没有上传完成，请稍后！'
        })
      }
      this.formData.image = imgUpload.fileList[0].url
    },
    // 获取页面数据
    async categoriesList() {
      const res = await categoriesList({
        _limit: this.limit,
        _start: this.start,
        title_contains: this.search.titleContains
      })
      console.log(141, res)
      this.categoriesData = res.data
      this.page = (this.start / this.limit) + 1
      // console.log(141, this.page)
    },
    // 分页
    changeCur(currentPage) {
      // console.log(currentPage)
      this.start = (currentPage - 1) * this.limit
      // 重新渲染
      this.categoriesList()
    },

    // 查询
    async searchFn() {
      this.categoriesList()
      const res = await categoriesCount({
        title_contains: this.search.titleContains
      })
      this.total = res.data
    },

    // 新增
    addFn() {
      this.dialogFormVisible = true
    },
    // 弹出框确定 新增/编辑
    async confirmFn() {
      // 通过校验
      this.$refs.formData.validate()
      if (this.formData.id) {
        // 更新图片
        this.updateImg()
        // 调用编辑按钮
        await updateCategory(this.formData)
      } else {
        // console.log(183, this.$refs.imgUpload)
        // 更新图片
        this.updateImg()
        // 调用新增接口
        await addCategories(this.formData)
        // console.log(170, res)
        // 判断页面最多条数时渲染到下一页面数据
        if (this.categoriesData.length === this.limit) {
          this.start += this.limit
          this.total += this.limit
        }
        // 获取图片最新地址
      }
      // 重新渲染
      this.categoriesList()
      // 关闭弹窗
      this.closeFn()
    },
    // 弹出窗重置
    closeFn() {
      this.dialogFormVisible = false
      // 重置
      this.$refs.formData.resetFields()
      // 清空表单
      this.formData = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.imgUpload.removeFn()
    },

    // 编辑
    async editFn(id) {
      this.dialogFormVisible = true
      // 回显数据
      const res = await getCategory(id)
      // console.log(res)
      this.formData = res.data
      // 头像回显
      this.$refs.imgUpload.fileList.push({
        url: this.formData.image
      })
      // 隐藏进度条
      this.$refs.imgUpload.percentage = 100
    },
    // 删除
    delFn(id) {
      this.$confirm('是否确定删除该条数据', '删除', {
        type: 'warninng'
      }).then(async() => {
        // 调用删除接口
        await delCategory(id)
        // 删除最后一条数据时优化

        if (this.categoriesData.length === 1 && this.page !== 1) {
          this.start -= this.limit
          this.total -= this.limit
        }
        // 重新渲染
        this.categoriesList()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin: 20px;
}
</style>
